<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Controller;

use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Goods\Entity\Goods;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\I18n\Translator;
use Shop\Form\GoodsSearchForm;

class SearchController extends AbstractActionController
{
    private $translator;
    private $entityManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager
    )
    {
        $this->translator   = $translator;
        $this->entityManager= $entityManager;
    }

    /**
     * 搜索
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $this->layout()->setVariable('titleName', $this->translator->translate('搜索'));

        $array = [];

        $array['searchForm'] = new GoodsSearchForm();

        $array['searchIndexPartial'] = $this->shopPlugin()->shopPartial('searchIndex');

        return $array;
    }

    /**
     * 商品搜索结果
     * @return array
     */
    public function goodsSearchAction()
    {
        $this->layout()->setVariable('titleName', $this->translator->translate('搜索结果'));

        $searchArray = [];

        $searchForm = new GoodsSearchForm();

        if($this->getRequest()->isGet()) {
            $data = $this->params()->fromQuery();
            $searchForm->setData($data);
            if($searchForm->isValid()) {
                $searchArray = $searchForm->getData();
            }
        }

        $sort = $this->params()->fromQuery('sort', '');
        if(!empty($sort) && in_array($sort, ['priceASC', 'priceDESC', 'clickASC', 'clickDESC', 'timeASC', 'timeDESC'])) {
            $searchArray['sort'] = $sort;
        }

        //搜索列表
        $page       = (int) $this->params()->fromQuery('page', 1);
        $query      = $this->entityManager->getRepository(Goods::class)->findShopSearchGoodsList($searchArray, $this->shopPlugin()->getUserLoginData('user_group_id'));
        $paginator  = $this->shopPlugin()->shopPaginator($query, $page, $this->shopPlugin()->shopPerPageNum('searchGoodsList'));

        return [
            'searchForm'    => $searchForm,
            'searchArray'   => $searchArray,
            'goodsList'     => $paginator
        ];
    }
}